import api from "./api";

function parseMenuTree(list: any[]) {
  const newList: any = [];
  // 处理一级菜单
  for (const item of list) {
    const { parentId, menuType, visible } = item;
    if (
      parentId === 0 &&
      (menuType === "M" || menuType === "C") &&
      visible === "0"
    ) {
      newList.push(item);
    }
  }

  // 处理二级菜单
  for (const item of list) {
    const { parentId, menuType, visible } = item;
    if (parentId !== 0 && menuType === "C" && visible === "0") {
      let parent = item;
      while (parent && parent.parentId !== 0) {
        // eslint-disable-next-line no-loop-func
        parent = list.find((val) => val.menuId === parent.parentId);
      }
      parent && parent !== item && parent.children.push(item);
    }
  }

  return newList;
}

function parseRoute(item: any) {
  const { url, menuName, children } = item;

  const name = menuName;
  const path = !url || url === "#" || url.startsWith("http") ? "/" + name : url;
  if (children && children.length) {
    return { name, path, routes: parseRouteList(children) };
  } else {
    return { name, path, url };
  }
}

function parseRouteList(tree: any[]) {
  const routes: any[] = [];
  for (const item of tree) {
    const route = parseRoute(item);
    routes.push(route);
  }
  return routes;
}

async function getRuoyiMenuList() {
  try {
    const resp = await fetch(api.menu, {
      method: "POST",
      body: JSON.stringify({}),
    });
    const list = await resp.json();
    const tree = parseMenuTree(list);
    const routes = parseRouteList(tree);
    return [
      {
        path: "/system/main",
        name: "系统首页",
        url: "/system/main",
      },
      ...routes,
    ];
  } catch (error) {
    console.error("Error fetching menu:", error);
  }
  return [];
}

export { getRuoyiMenuList };
